import { Action,Db } from 'uokay'
import Message from '../b/Message'
import axios from 'axios'
import database from '../database'
export default class WsAction extends Action {
    __initial__ () {
        this.deny = ['sock']
        this.sock = new WebSocket('ws://localhost:3001')
        this.sock.onopen = () => { this.onSockOpen() }
        this.sock.onmessage = (e) => { this.onSockMessage(JSON.parse(e.data)) }
        this.sock.onclose = () => { this.onSockClose() }
        this.sock.onerror = (err) => {console.log(err)}
    }
    reopen () {
        if (this.sock == null) {
            this.sock = new WebSocket('ws://localhost:3001')
            this.sock.onopen = () => { this.onSockOpen() }
            this.sock.onmessage = (data) => { this.onSockMessage(JSON.parse(data)) }
            this.sock.onclose = () => { this.onSockClose() }
        }
    }
    send (message) {
        if (this.sock == null) {
            this.reopen()
        }
        message.set_user(sessionStorage.getItem('id'))
        this.sock.send(message.to_json())

    }
    onSockOpen () {
        let message = new Message('login', 'user login')
        this.send(message)
    }
    onSockMessage (data) {
        switch (data.code) {
            case 'error':
                console.log(data.message)
                break;
            case 'login':
                console.log('绑定成功')
                break;
            case 'primary':
                //在2.0中新增设计调用trigger方法触发Action方法，okay为当前活跃组件,使用pipe
                console.log('primary')
                let sender = data.data.sender
                let msg = data.data.msg
                let db = Db.i(database)
                db.table('et_conversation').where('friend_id', sender).find()
                    .then(result => {
                        if(result.length > 0) {
                            if (this.okays.messlist && Object.prototype.toString.call(this.okays.messlist) == '[object Set]') {
                                for(let conv of this.okays.messlist) {
                                    let target = null
                                    for(let dt of conv.data.conversations) {
                                        dt.friend_id == result[0].id?target = dt:null
                                    }
                                    if(target) {
                                        //如果有该对话
                                        target.isread = false
                                    }else {
                                        conv.data.conversations.push({ friend_id:result[0].id,isread:false })
                                    }
                                }
                            }else if(this.okays.messlist) {
                                let conv = this.okays.messlist
                                let target = null
                                for(let dt of conv.data.conversations) {
                                    dt.friend_id == result[0].id?target = dt:null
                                }
                                if(target) {
                                    //如果有该对话
                                    target.isread = false
                                }else {
                                    conv.data.conversations.push({ friend_id:result[0].id,isread:false })
                                }
                            }
                            return Promise.resolve(result[0].id)
                        }else {
                            return db.table('et_conversation').insert({ friend_id: sender, createtime: new Date().getTime() })
                                .then(result => {
                                    return db.table('et_conversation').where('friend_id', sender).find()
                                        .then(result => {
                                            console.log(result)
                                            if (this.okays.messlist && Object.prototype.toString.call(this.okays.messlist) == '[object Set]') {
                                                for(let conv of this.okays.messlist) {
                                                    let target = null
                                                    for(let dt of conv.data.conversations) {
                                                        dt.friend_id == result[0].id?target = dt:null
                                                    }
                                                    if(target) {
                                                        //如果有该对话
                                                        target.isread = false
                                                    }else {
                                                        conv.data.conversations.push({ friend_id:result[0].id,isread:false })
                                                    }
                                                }
                                            }else if(this.okays.messlist) {
                                                let conv = this.okays.messlist
                                                let target = null
                                                for(let dt of conv.data.conversations) {
                                                    dt.friend_id == result[0].id?target = dt:null
                                                }
                                                if(target) {
                                                    //如果有该对话
                                                    target.isread = false
                                                }else {
                                                    conv.data.conversations.push({ friend_id:result[0].id,isread:false })
                                                }
                                            }
                                            return  Promise.resolve(result[0].id)
                                        }).catch(error => {
                                            return Promise.reject(error)
                                    })
                                })
                        }
                    }).then(result => {
                        let mess = { sender: sender, convid: result, receiver: sessionStorage.getItem('id'), message: msg,createtime:new Date().getTime() }
                     db.table('et_message').insert(mess)
                         .then(result => {
                             if (this.okays.primary && Object.prototype.toString.call(this.okays.primary)  == '[object Set]') {
                                 for(let primary of this.okays.primary) {
                                     if (primary.data.$route.user_id == sender) {
                                         primary.data.messages.push(mess)
                                     }
                                 }
                             }else if(this.okays.primary){
                                 this.okays.primary.data.messages.push(mess)
                             }
                         })
                }).catch(error => {
                    console.log(error)
                })
                break;
        }
    }
    onSockClose () {
        console.log(this)
        this.sock.close()
        this.sock = null
        axios.post('/users/logout',{
            id: sessionStorage.getItem('id')
        }).then(response => {
            if (response.data.code == 2000) {
                alert('退出应用')
            }
        }).catch(err => {
            console.error(err)
        })
    }
    sendMessage(okay, event, pipe) {
        let message = pipe.get('message')
        console.log('send message')
        this.send(message)
    }
}